# ================================
# 应用启动脚本 - 后端 + 前端
# ================================

param(
    [switch]$BackendOnly,
    [switch]$FrontendOnly,
    [switch]$Help
)

if ($Help) {
    Write-Host "应用启动脚本使用说明:" -ForegroundColor Green
    Write-Host "  .\StartApp.ps1           # 启动后端和前端"
    Write-Host "  .\StartApp.ps1 -BackendOnly   # 仅启动后端"
    Write-Host "  .\StartApp.ps1 -FrontendOnly  # 仅启动前端"
    Write-Host "  .\StartApp.ps1 -Help          # 显示帮助"
    exit 0
}

$rootPath = "d:\2025\JGSY.PP\Project\JGSY.CMS.LowCode.Platform"
$frontendPath = "$rootPath\wwwroot\frontend"

Write-Host "======================================" -ForegroundColor Green
Write-Host "🚀 CMS Low-Code Platform 应用启动" -ForegroundColor Green
Write-Host "======================================" -ForegroundColor Green
Write-Host "项目路径: $rootPath" -ForegroundColor Cyan
Write-Host "前端路径: $frontendPath" -ForegroundColor Cyan
Write-Host ""

# 检查项目文件
if (-not (Test-Path "$rootPath\JGSY.CMS.LowCode.Platform.csproj")) {
    Write-Host "❌ 后端项目文件不存在！" -ForegroundColor Red
    exit 1
}

if (-not (Test-Path "$frontendPath\package.json")) {
    Write-Host "❌ 前端项目文件不存在！" -ForegroundColor Red
    exit 1
}

# 函数：启动后端
function Start-Backend {
    Write-Host "🔧 启动后端 ASP.NET Core 应用..." -ForegroundColor Blue
    
    # 切换到项目根目录
    Set-Location $rootPath
    
    # 检查编译
    Write-Host "📦 检查后端编译状态..." -ForegroundColor Yellow
    $buildResult = dotnet build --verbosity quiet
    if ($LASTEXITCODE -ne 0) {
        Write-Host "❌ 后端编译失败！" -ForegroundColor Red
        dotnet build  # 显示详细错误
        return $false
    }
    Write-Host "✅ 后端编译成功" -ForegroundColor Green
    
    # 启动后端（后台运行）
    Write-Host "🚀 启动后端服务器..." -ForegroundColor Blue
    $backendJob = Start-Job -ScriptBlock {
        Set-Location $using:rootPath
        dotnet run --urls "http://localhost:5153"
    }
    
    # 等待后端启动
    Write-Host "⏳ 等待后端服务器启动..." -ForegroundColor Yellow
    $maxWait = 30
    $waited = 0
    $backendReady = $false
    
    while ($waited -lt $maxWait -and -not $backendReady) {
        Start-Sleep -Seconds 2
        $waited += 2
        try {
            $response = Invoke-WebRequest -Uri "http://localhost:5153/swagger" -Method GET -TimeoutSec 3 -ErrorAction SilentlyContinue
            if ($response.StatusCode -eq 200) {
                $backendReady = $true
            }
        } catch {
            Write-Host "." -NoNewline -ForegroundColor Yellow
        }
    }
    
    if ($backendReady) {
        Write-Host ""
        Write-Host "✅ 后端服务器启动成功！" -ForegroundColor Green
        Write-Host "   🌐 API地址: http://localhost:5153" -ForegroundColor Cyan
        Write-Host "   📚 Swagger: http://localhost:5153/swagger" -ForegroundColor Cyan
        return $backendJob
    } else {
        Write-Host ""
        Write-Host "❌ 后端服务器启动超时" -ForegroundColor Red
        Stop-Job $backendJob
        Remove-Job $backendJob
        return $false
    }
}

# 函数：启动前端
function Start-Frontend {
    Write-Host "🔧 启动前端 React 应用..." -ForegroundColor Blue
    
    # 切换到前端目录
    Set-Location $frontendPath
    
    # 检查 node_modules
    if (-not (Test-Path "node_modules")) {
        Write-Host "📦 安装前端依赖..." -ForegroundColor Yellow
        if (Get-Command pnpm -ErrorAction SilentlyContinue) {
            pnpm install
        } elseif (Get-Command npm -ErrorAction SilentlyContinue) {
            npm install
        } else {
            Write-Host "❌ 未找到 npm 或 pnpm！请先安装 Node.js" -ForegroundColor Red
            return $false
        }
        
        if ($LASTEXITCODE -ne 0) {
            Write-Host "❌ 前端依赖安装失败！" -ForegroundColor Red
            return $false
        }
        Write-Host "✅ 前端依赖安装成功" -ForegroundColor Green
    }
    
    # 启动前端开发服务器
    Write-Host "🚀 启动前端开发服务器..." -ForegroundColor Blue
    $frontendJob = Start-Job -ScriptBlock {
        Set-Location $using:frontendPath
        if (Get-Command pnpm -ErrorAction SilentlyContinue) {
            pnpm start
        } else {
            npm start
        }
    }
    
    # 等待前端启动
    Write-Host "⏳ 等待前端服务器启动..." -ForegroundColor Yellow
    $maxWait = 45
    $waited = 0
    $frontendReady = $false
    
    while ($waited -lt $maxWait -and -not $frontendReady) {
        Start-Sleep -Seconds 3
        $waited += 3
        try {
            $response = Invoke-WebRequest -Uri "http://localhost:3000" -Method GET -TimeoutSec 3 -ErrorAction SilentlyContinue
            if ($response.StatusCode -eq 200) {
                $frontendReady = $true
            }
        } catch {
            Write-Host "." -NoNewline -ForegroundColor Yellow
        }
    }
    
    if ($frontendReady) {
        Write-Host ""
        Write-Host "✅ 前端服务器启动成功！" -ForegroundColor Green
        Write-Host "   🌐 应用地址: http://localhost:3000" -ForegroundColor Cyan
        return $frontendJob
    } else {
        Write-Host ""
        Write-Host "❌ 前端服务器启动超时，但可能仍在启动中" -ForegroundColor Yellow
        Write-Host "   请手动检查: http://localhost:3000" -ForegroundColor Cyan
        return $frontendJob
    }
}

# 主启动逻辑
$backendJob = $null
$frontendJob = $null

try {
    if (-not $FrontendOnly) {
        $backendJob = Start-Backend
        if (-not $backendJob) {
            Write-Host "❌ 后端启动失败，退出..." -ForegroundColor Red
            exit 1
        }
    }
    
    if (-not $BackendOnly) {
        Start-Sleep -Seconds 2  # 给后端一点时间
        $frontendJob = Start-Frontend
    }
    
    # 显示启动结果
    Write-Host ""
    Write-Host "🎉 应用启动完成！" -ForegroundColor Green
    Write-Host ""
    Write-Host "📊 服务状态:" -ForegroundColor Blue
    if ($backendJob) {
        Write-Host "  ✅ 后端: http://localhost:5153 (Swagger: /swagger)" -ForegroundColor Green
    }
    if ($frontendJob) {
        Write-Host "  ✅ 前端: http://localhost:3000" -ForegroundColor Green
    }
    
    Write-Host ""
    Write-Host "🛡️ 测试端点:" -ForegroundColor Magenta
    Write-Host "  📍 POST http://localhost:5153/api/auth/register - 用户注册"
    Write-Host "  📍 POST http://localhost:5153/api/auth/login - 用户登录"
    Write-Host "  📍 GET  http://localhost:5153/api/ConfigurationMigration/status - 配置状态"
    
    Write-Host ""
    Write-Host "⚠️ 按 Ctrl+C 停止所有服务" -ForegroundColor Yellow
    Write-Host ""
    
    # 等待用户中断
    while ($true) {
        Start-Sleep -Seconds 5
        
        # 检查作业状态
        if ($backendJob -and $backendJob.State -eq "Failed") {
            Write-Host "❌ 后端服务异常退出" -ForegroundColor Red
            break
        }
        if ($frontendJob -and $frontendJob.State -eq "Failed") {
            Write-Host "❌ 前端服务异常退出" -ForegroundColor Red
            break
        }
    }
    
} catch {
    Write-Host "❌ 启动过程中出现错误: $($_.Exception.Message)" -ForegroundColor Red
} finally {
    # 清理作业
    Write-Host ""
    Write-Host "🛑 正在停止服务..." -ForegroundColor Yellow
    
    if ($backendJob) {
        Stop-Job $backendJob -ErrorAction SilentlyContinue
        Remove-Job $backendJob -ErrorAction SilentlyContinue
    }
    if ($frontendJob) {
        Stop-Job $frontendJob -ErrorAction SilentlyContinue  
        Remove-Job $frontendJob -ErrorAction SilentlyContinue
    }
    
    Write-Host "✅ 服务已停止" -ForegroundColor Green
}
